<template>
  <div class="fixed inset-0 bg-gradient-to-br from-green-400 to-emerald-600 flex items-center justify-center">
    <button 
      @click="$router.push('/')" 
      class="absolute top-4 left-4 px-4 py-2 bg-white/20 backdrop-blur-sm rounded-full text-white hover:bg-white/30 transition-all duration-300 flex items-center space-x-2 z-50"
    >
      <span>←</span>
      <span>返回选择</span>
    </button>

    <!-- 游戏状态栏 -->
    <div class="absolute top-4 right-4 flex space-x-4 z-50">
      <div class="stats-card">
        <span class="text-lg text-gray-600">得分</span>
        <span class="text-3xl font-bold text-purple-600 animate-pulse">{{ score }}</span>
      </div>
      <div class="stats-card">
        <span class="text-lg text-gray-600">最高分</span>
        <span class="text-3xl font-bold text-purple-600">{{ highScore }}</span>
      </div>
    </div>

    <!-- 游戏区域 -->
    <div class="bg-white bg-opacity-95 rounded-3xl shadow-2xl p-8 w-full max-w-2xl">
      <h1 class="text-4xl font-extrabold text-center mb-8 text-transparent bg-clip-text bg-gradient-to-r from-green-500 to-emerald-600 animate-gradient">
        贪吃蛇
      </h1>

      <div 
        class="game-board relative bg-emerald-100 rounded-xl overflow-hidden"
        :style="{ width: `${boardSize}px`, height: `${boardSize}px` }"
      >
        <!-- 蛇身 -->
        <div
          v-for="segment in snake"
          :key="`${segment.x}-${segment.y}`"
          class="snake-segment absolute bg-emerald-500 rounded-lg transform transition-all duration-100"
          :style="{
            left: `${segment.x * gridSize}px`,
            top: `${segment.y * gridSize}px`,
            width: `${gridSize - 2}px`,
            height: `${gridSize - 2}px`
          }"
        ></div>

        <!-- 食物 -->
        <div
          class="food absolute transform transition-all duration-200"
          :style="{
            left: `${food.x * gridSize}px`,
            top: `${food.y * gridSize}px`,
            width: `${gridSize - 2}px`,
            height: `${gridSize - 2}px`
          }"
        >
          🍎
        </div>
      </div>

      <!-- 控制按钮 -->
      <div class="mt-8 grid grid-cols-3 gap-4 max-w-xs mx-auto" v-if="isMobile">
        <button @click="changeDirection('up')" class="control-btn">↑</button>
        <div></div>
        <button @click="changeDirection('down')" class="control-btn">↓</button>
        <button @click="changeDirection('left')" class="control-btn">←</button>
        <button @click="startGame" class="control-btn">
          {{ gameActive ? '暂停' : '开始' }}
        </button>
        <button @click="changeDirection('right')" class="control-btn">→</button>
      </div>

      <!-- 开始游戏提示 -->
      <div 
        v-if="!gameActive && !gameOver" 
        class="absolute inset-0 flex items-center justify-center bg-black/50 backdrop-blur-sm rounded-xl"
      >
        <div class="text-center">
          <h2 class="text-3xl font-bold text-white mb-6">准备开始</h2>
          <div class="text-xl text-white space-y-2 mb-8">
            <p>使用方向键或 WASD 控制蛇的移动</p>
            <p>吃到食物可以增长和得分</p>
            <p>撞到墙壁或自己会结束游戏</p>
          </div>
          <button
            @click="startGame"
            class="bg-gradient-to-r from-green-500 to-emerald-600 text-white font-bold py-3 px-8 rounded-full transition-all duration-300 transform hover:scale-110"
          >
            开始游戏
          </button>
        </div>
      </div>

      <!-- 游戏结束界面 -->
      <div 
        v-if="gameOver" 
        class="absolute inset-0 flex items-center justify-center bg-black/50 backdrop-blur-sm rounded-xl"
      >
        <div class="bg-white rounded-3xl p-8 text-center transform animate-bounce-slow">
          <h2 class="text-3xl font-bold text-red-600 mb-6 animate-wiggle">
            游戏结束!
          </h2>
          <p class="text-xl text-gray-700 mb-2">最终得分: {{ score }}</p>
          <p class="text-lg text-purple-600 mb-8">历史最高分: {{ highScore }}</p>
          <button
            @click="startGame"
            class="bg-gradient-to-r from-green-500 to-emerald-600 text-white font-bold py-3 px-8 rounded-full transition-all duration-300 transform hover:scale-110"
          >
            再玩一次
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue';

interface Position {
  x: number;
  y: number;
}

const gridSize = 20; // 每个格子的大小
const boardSize = 400; // 游戏板大小
const gridCount = boardSize / gridSize; // 网格数量

const snake = ref<Position[]>([{ x: 5, y: 5 }]);
const food = ref<Position>({ x: 10, y: 10 });
const direction = ref<string>('right');
const gameActive = ref(false);
const gameOver = ref(false);
const score = ref(0);
const highScore = ref(0);
const gameLoop = ref<ReturnType<typeof setInterval> | null>(null);
const isMobile = ref(false);

// 检查是否是移动设备
onMounted(() => {
  isMobile.value = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
  window.addEventListener('keydown', handleKeyPress);
});

onUnmounted(() => {
  window.removeEventListener('keydown', handleKeyPress);
  if (gameLoop.value) {
    clearInterval(gameLoop.value);
  }
});

const handleKeyPress = (event: KeyboardEvent) => {
  if (!gameActive.value) return;

  switch (event.key.toLowerCase()) {
    case 'arrowup':
    case 'w':
      if (direction.value !== 'down') direction.value = 'up';
      break;
    case 'arrowdown':
    case 's':
      if (direction.value !== 'up') direction.value = 'down';
      break;
    case 'arrowleft':
    case 'a':
      if (direction.value !== 'right') direction.value = 'left';
      break;
    case 'arrowright':
    case 'd':
      if (direction.value !== 'left') direction.value = 'right';
      break;
  }
};

const changeDirection = (newDirection: string) => {
  const opposites = {
    up: 'down',
    down: 'up',
    left: 'right',
    right: 'left'
  };
  
  if (opposites[newDirection as keyof typeof opposites] !== direction.value) {
    direction.value = newDirection;
  }
};

const generateFood = () => {
  let newFood: Position;
  do {
    newFood = {
      x: Math.floor(Math.random() * gridCount),
      y: Math.floor(Math.random() * gridCount)
    };
  } while (snake.value.some(segment => segment.x === newFood.x && segment.y === newFood.y));
  
  food.value = newFood;
};

const moveSnake = () => {
  const head = { ...snake.value[0] };

  switch (direction.value) {
    case 'up':
      head.y--;
      break;
    case 'down':
      head.y++;
      break;
    case 'left':
      head.x--;
      break;
    case 'right':
      head.x++;
      break;
  }

  // 检查碰撞
  if (
    head.x < 0 ||
    head.x >= gridCount ||
    head.y < 0 ||
    head.y >= gridCount ||
    snake.value.some(segment => segment.x === head.x && segment.y === head.y)
  ) {
    endGame();
    return;
  }

  snake.value.unshift(head);

  // 检查是否吃到食物
  if (head.x === food.value.x && head.y === food.value.y) {
    score.value += 10;
    generateFood();
  } else {
    snake.value.pop();
  }
};

const startGame = () => {
  if (gameActive.value) {
    gameActive.value = false;
    if (gameLoop.value) clearInterval(gameLoop.value);
    return;
  }

  // 重置游戏状态
  snake.value = [{ x: 5, y: 5 }];
  direction.value = 'right';
  score.value = 0;
  gameOver.value = false;
  gameActive.value = true;
  generateFood();

  // 开始游戏循环
  gameLoop.value = setInterval(() => {
    if (gameActive.value) {
      moveSnake();
    }
  }, 150);
};

const endGame = () => {
  gameActive.value = false;
  gameOver.value = true;
  if (gameLoop.value) {
    clearInterval(gameLoop.value);
  }
  if (score.value > highScore.value) {
    highScore.value = score.value;
  }
};
</script>

<style scoped>
.stats-card {
  @apply flex flex-col items-center p-4 bg-white/90 rounded-xl shadow-md backdrop-blur-sm;
}

.game-board {
  border: 4px solid #059669;
}

.snake-segment {
  margin: 1px;
  box-shadow: 0 0 4px rgba(0, 0, 0, 0.2);
}

.food {
  font-size: 1.2rem;
  display: flex;
  align-items: center;
  justify-content: center;
  animation: bounce 1s infinite;
}

.control-btn {
  @apply bg-emerald-500 text-white text-2xl font-bold p-4 rounded-xl
         hover:bg-emerald-600 active:bg-emerald-700 transition-colors duration-200
         focus:outline-none focus:ring-2 focus:ring-emerald-500 focus:ring-opacity-50;
}

@keyframes bounce {
  0%, 100% { transform: translateY(0); }
  50% { transform: translateY(-5px); }
}

.animate-gradient {
  background-size: 200% 200%;
  animation: gradient 15s ease infinite;
}

@keyframes gradient {
  0% { background-position: 0% 50%; }
  50% { background-position: 100% 50%; }
  100% { background-position: 0% 50%; }
}
</style>
